function! bootstrap#fullscreen#candidates() abort
    let pattern = [ 'gvimfullscreen.dll.x64', 'gvimfullscreen.dll' ]
    let candidates = map(pattern, {
                \   _, val -> globpath(&rtp, val, v:false, v:false)
                \ })
    let candidates = filter(candidates, {
                \   _, val -> filereadable(val)
                \ })
    if empty(candidates)
        let g:vimfiles_cache = get(g:, 'vimfiles_cache', '~/.cache/vimfiles/repos/github.com')
        let candidates = globpath(g:vimfiles_cache, '**/gvimfullscreen.dll.x64', v:true, v:true)
    endif
    return candidates
endfunction

function! bootstrap#fullscreen#toggle() abort
    call SpaceVim#logger#info('calling bootstrap#fullscreen#toggle()')
    if has('win32')
        if !exists('g:gvimfullscreen_libname')
            let candidates = bootstrap#fullscreen#candidates() 
            if !empty(candidates)
                echomsg "candidates = " . join(candidates, "\n")
                let g:gvimfullscreen_libname = candidates[0]
                if filereadable(g:gvimfullscreen_libname)
                    let g:gvimfullscreen_libpath = g:gvimfullscreen_libname
                endif
                if !executable(g:gvimfullscreen_libpath)
                    let g:gvimfullscreen_directory = fnamemodify(g:gvimfullscreen_libpath, ':p:h')
                    let $PATH = g:gvimfullscreen_directory . ';' . $PATH
                endif
            endif
        endif
        call libcallnr(g:gvimfullscreen_libpath, 'ToggleFullScreen', 1)
    else
        call SpaceVim#logger#info('use wmctrl to toggle fullscreen')
        call system("wmctrl -ir " . v:windowid . " -b toggle,fullscreen")
    endif
endfunction

function! bootstrap#fullscreen#setup() abort
    call SpaceVim#logger#info('calling bootstrap#fullscreen#setup()')
    command! ToggleFullScreen call bootstrap#fullscreen#toggle() 
    noremap <silent> <plug>(toggle-fullscreen) :ToggleFullScreen<cr>
    nnoremap <m-cr> <plug>(toggle-fullscreen)
    nnoremap <F11> <plug>(toggle-fullscreen)
    call SpaceVim#mapping#space#def('nnoremap', ['T', 'F'],
                \  'call bootstrap#fullscreen#toggle()',
                \ 'fullscreen-frame', 1)
endfunction

function! bootstrap#fullscreen#after() abort
    if !empty(maparg("<F11>"))
        call SpaceVim#logger#info('maparg("<F11>") from "' . maparg("<F11>") . '" to "<plug>(toggle-fullscreen)"')
        nnoremap <F11> <plug>(toggle-fullscreen)
        call SpaceVim#logger#info('maparg("<F11>") now is "' . maparg("<F11>") . '"')
    endif
endfunction


